package com.ford.trade.bigCompany;

import com.ford.trade.dto.QueryDTO;
import com.ford.trade.entity.Game;
import com.ford.trade.entity.PeiLv2;
import com.ford.trade.service.Game500Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.scheduler.BloomFilterDuplicateRemover;
import us.codecraft.webmagic.scheduler.QueueScheduler;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author :  zhangfutao
 * @version :  V-1.0
 * @description :
 * @date :   2022/5/24 14:33
 */
@RestController
public class BigCompanyController {
    @Resource
    private Game500Service game500Service;
    @Resource
    private Peilv2Service peilv2Service;

    @PostMapping("getPeilv2")
    public void getPeilv(@RequestBody QueryDTO queryDTO) throws ParseException {
        //获取一天的比赛
        List<Game> games = game500Service.findAllByDateBetten(queryDTO.getDate());
        if (CollectionUtils.isEmpty(games)) {
            return;
        }
        List<String> urls = new ArrayList<>();
        if ("1".equals(queryDTO.getGetResult())){
            for (Game game : games) {
                List<PeiLv2> peiLv2s = peilv2Service.findByIndexId(game.getIndexId());
                if (!CollectionUtils.isEmpty(peiLv2s)){
                    for (PeiLv2 peiLv2 : peiLv2s) {
                        peiLv2.setResult(game.getResult());
                        peilv2Service.save(peiLv2);
                    }
                }
            }
        }else {
            if ("oupei".equals(queryDTO.getType())) {
                for (Game game : games) {
                    urls.add("https://odds.500.com/fenxi/ouzhi-" + game.getIndexId() + ".shtml" + "?order=0");
                }
            } else if ("yapei".equals(queryDTO.getType())) {
                for (Game game : games) {
                    urls.add("https://odds.500.com/fenxi/yazhi-" + game.getIndexId() + ".shtml");
                }
            }
            String[] objects = new String[games.size()];
            String[] array = urls.toArray(objects);
            Peilv2Processor peilv2Processor = new Peilv2Processor();
            peilv2Processor.setCookie(queryDTO.getCookie());
            peilv2Processor.setPeilv2Service(peilv2Service);
            peilv2Processor.setDate(queryDTO.getDate());
            peilv2Processor.setGames(games);
            peilv2Processor.setType(queryDTO.getType());
            Spider.create(peilv2Processor)
                    .addUrl(array)
                    .setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(1000)))
                    .thread(32)
                    .run();
        }
    }
}
